package com.hoperun.broadcastserver.slice;

import com.hoperun.broadcastserver.Log;
import com.hoperun.broadcastserver.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

public class MainAbilitySlice extends AbilitySlice {
    Text receiveText;
    private int broadcastPort = 8888;     //端口
    private String broadcastIp = "10.50.70.255";//"255.255.255.255";       //广播范围
    EventHandler eventHandler;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        receiveText = (Text) findComponentById(ResourceTable.Id_receiveText);
        eventHandler = new EventHandler(EventRunner.create());
        try {
            receiveText.setText(receiveText.getText() + "\n local :" + getPhoneBroadcast());
        } catch (SocketException e) {
            e.printStackTrace();
        }

        eventHandler.postTask(this::receive);
    }

    public void receive() {
        try (DatagramSocket socket = new DatagramSocket(broadcastPort)) {
            Log.println("  receive -->port:%s, address:%s, localPort:%s", socket.getPort(), socket.getLocalAddress(), socket.getLocalPort());
            byte[] ackBuf = new byte[4096];
//            DatagramPacket ackPacket = new DatagramPacket(ackBuf, ackBuf.length);
            InetAddress address = InetAddress.getByName(broadcastIp);
//            InetSocketAddress socketAddress = InetSocketAddress.createUnresolved(broadcastIp,broadcastPort);
            DatagramPacket ackPacket = new DatagramPacket(ackBuf, ackBuf.length, address,broadcastPort);
            socket.receive(ackPacket);
            String receiveStr = new String(ackPacket.getData(), StandardCharsets.UTF_8);
            String receiveIP = ackPacket.getAddress().getHostAddress();

            appendReceive(receiveIP + " -->" + receiveStr);

//            if (getAbility().isTerminating()) {
//                Log.println("cancel receive task");
//                return;
//            }
            eventHandler.postTask(this::receive);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void appendReceive(String str) {
        String time = simpleDateFormat.format(new Date());
        String builder = receiveText.getText() + "\n" +
                time + " : " + str;

        Log.println("appendReceive %s", builder);
        getUITaskDispatcher().asyncDispatch(() -> receiveText.setText(builder));
    }

    /**
     * 获取当前移动设备的广播地址
     * 返回示例：192.168.11.255
     */
    private String getPhoneBroadcast() throws SocketException {
        System.setProperty("java.net.preferIPv4Stack", "true");
        StringBuilder strIp = new StringBuilder();
        for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum.hasMoreElements(); ) {
            NetworkInterface ni = niEnum.nextElement();
            if (!ni.isLoopback()) {
                for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
                    if (interfaceAddress.getBroadcast() != null) {
                        String str = interfaceAddress.getBroadcast().toString().substring(1);
                        strIp.append(str).append("\n");
                    }
                    if (interfaceAddress.getAddress() != null) {
                        String str = interfaceAddress.getAddress().getHostAddress();
                        strIp.append(str).append("\n");
                    }
                }
            }
        }
        return strIp.toString();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
